package com.collect.tanzania.zhiScene.zhiCheckIn;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Location;
import android.util.Log;
import android.view.View;
import android.widget.TextClock;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.Task;
import com.lihang.ShadowLayout;
import com.collect.tanzania.R;
import com.collect.tanzania.zhiBase.BaseActivity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRCheckInOutEntity;
import com.collect.tanzania.zhiBean.zhiReceive.ZHIRSysConfigEntity;
import com.collect.tanzania.zhiBean.zhiSend.ZHISCheckInOutEntity;
import com.collect.tanzania.zhiBean.zhiSend.ZHISendEntity;
import com.collect.tanzania.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.tanzania.zhiHelper.ZHICallLogHelper;
import com.collect.tanzania.zhiHelper.ZHIMainProcessHelper;
import com.collect.tanzania.zhiScene.zhiWidget.zhiCutdown.ZHITimerTextView;
import com.collect.tanzania.zhiScene.zhiWidget.zhiDialog.ZHIDialogMessage;
import com.collect.tanzania.zhiScene.zhiWidget.zhiNavigationBar.ZHINavigationBar;
import com.zhi.syc.data_applist.ASGpsManagerGms;

import java.util.ArrayList;
import butterknife.BindView;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_CHECK_IN)
public class ZHICheckInActivity extends BaseActivity<ZHICheckInPresenter> implements ZHICheckInContract.View {

    @BindView(R.id.navigationBar)
    ZHINavigationBar navigationBar;

    @BindView(R.id.tv_ci_waiting_cutdown)
    TextView tv_ci_waiting_cutdown;

    @BindView(R.id.tv_ci_check_state)
    ZHITimerTextView tv_ci_check_state;

    @BindView(R.id.sl_ci_check_state)
    ShadowLayout sl_ci_check_state;

    @BindView(R.id.tc_ci_cur_service_time)
    TextClock tc_ci_cur_service_time;

    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_check_in;
    }

    @Override
    protected void initInjector() {
        mActivityComponent.inject(this);
    }

    @SuppressLint("NewApi")
    @Override
    protected void initView() {
        try {
            tc_ci_cur_service_time.setFormat24Hour("yyyy-MM-dd EEEE aa HH:mm:ss");
            tc_ci_cur_service_time.setFormat12Hour("yyyy-MM-dd EEEE aa HH:mm:ss");

            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

            navigationBar.showRight().setCenterText("Clock In/Out").setRightImgage(R.drawable.ic_111).setBarClickListener(new ZHINavigationBar.OnNavigationBarClickListener() {
                @Override
                public void onNavigationBarLeftClick(View v) {
                    if (tv_ci_check_state.getText().toString().trim().equalsIgnoreCase("Clock In")) {
                        ZHIDialogMessage.showDialog(
                                getActivity(),
                                "Tips",
                                "Are you sure you don't clock in?",
                                "Later",
                                "Clock In",
                                tag -> {
                                    if (0 == tag) {
                                        toGoBack();
                                    } else if (1 == tag) {
                                        getCurLocation();
                                    }
                                });
                        return;
                    }
                    toGoBack();
                }

                @Override
                public void onNavigationBarRightClick(View v) {
                    ZHICheckInReduce.mFromCheckInPage = true;
                    ZHIProjectRouter.toCheckInHistory();
                }
            });

            tv_ci_check_state.setOnClickListener(v -> {
                try {
                    if (tv_ci_check_state.getText().toString().trim().contains("Clock In")) {
                        ZHIDialogMessage.showDialog(
                                getActivity(),
                                "Tips",
                                "Are you sure you want to clock in for work?",
                                "Cancel",
                                "Confirm",
                                tag -> {
                                    if (1 == tag) {
                                        getCurLocation();
                                    }
                                });
                        return;
                    }
                    if (tv_ci_check_state.getText().toString().trim().contains("Clock Out")) {
                        ZHIDialogMessage.showDialog(
                                getActivity(),
                                "Tips",
                                "Are you sure you want to clock out for work?",
                                "Cancel",
                                "Confirm",
                                tag -> {
                                    if (1 == tag) {
                                        toCheckInOut();
                                    }
                                });
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            //查询状态
            getCheckState();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        cleanTimer();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            cleanTimer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onGetErrorInfo(String apiName) {
        try {
            if (apiName.equalsIgnoreCase("checkInOut")) {
                resetCheckInUI();
                //查询状态
                getCheckState();
            } else if (apiName.equalsIgnoreCase("getCheckState")) {
                resetCheckInUI();
            } else if (apiName.equalsIgnoreCase("getCheckStateWhenCheckedCompleted")) {
                resetCheckInUI();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onGetCheckState(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
            if (zhirCheckInOutEntity.isToCheckIn()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText("Clock In");
                navigationBar.setCenterText("Clock In");

            } else if (zhirCheckInOutEntity.isToCheckOut()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText("Clock Out");
                navigationBar.setCenterText("Clock Out");

            } else {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
                tv_ci_check_state.setText("Completed");
                navigationBar.setCenterText("Clock In/Out");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onGetCheckStateWhenCheckedCompleted(ZHIRCheckInOutEntity zhirCheckInOutEntity) {
        try {
            resetCheckInUI();

            if (zhirCheckInOutEntity.isToCheckIn()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText("Clock In");
                navigationBar.setCenterText("Clock In");
                return;

            } else if (zhirCheckInOutEntity.isToCheckOut()) {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_color_0));
                tv_ci_check_state.setText("Clock Out");
                navigationBar.setCenterText("Clock Out");

            } else {
                sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
                tv_ci_check_state.setText("Completed");
                navigationBar.setCenterText("Clock In/Out");
            }

            ZHIProjectRouter.toCheckInHistoryForLogin();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCheckInOut() {
        //查询状态
        if (mPresenter != null) {
            mPresenter.getCheckStateWhenCheckedCompleted(getActivity(), new ZHISendEntity());
        }
    }

    @Override
    public void onGetCheckHistory(ArrayList<ZHIRCheckInOutEntity> zhirCheckInOutEntityArrayList) {

    }

    @Override
    public void onGetAppConfig(ZHIRSysConfigEntity zhirSysConfigEntity) {

    }

    private void toGoBack() {
        tv_ci_check_state.stopRun();
        if (ZHICheckInReduce.mFromLoginSuccess) {
            ZHICheckInReduce.mFromLoginSuccess = false;
            handlerLoginResult();
        } else {
            finish();
        }
    }

    @SuppressLint("SetTextI18n")
    private void resetCheckInUI() {
        tv_ci_check_state.stopRun();
        tv_ci_check_state.setText("Start");
        sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
        tv_ci_waiting_cutdown.setVisibility(View.GONE);
    }

    private void getCheckState() {
        //查询状态
        if (mPresenter != null) {
            mPresenter.getCheckState(getActivity(), new ZHISendEntity());
        }
    }

    @SuppressLint("SetTextI18n")
    private void getCurLocation() {
        tv_ci_check_state.setOnTimerCompleted(this::toCheckInOut);
        tv_ci_waiting_cutdown.setVisibility(View.VISIBLE);
        sl_ci_check_state.setLayoutBackground(getResources().getColor(R.color.theme_black_2));
        tv_ci_check_state.beginRun();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return;
        }
        Task<Location> locationTask = fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, null);
        locationTask.addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                Location location = task.getResult();
                if (location != null) {
                    Address address = ASGpsManagerGms.getInstance().getAccuracyAddress(getActivity(), location);
                    if (address != null) {
                        String mAddress = address.getAddressLine(0);
                        String mLongitude = location.getLongitude() + "";
                        String mLatitude = location.getLatitude() + "";

                        ASGpsManagerGms.getInstance().mAddress = mAddress;
                        ASGpsManagerGms.getInstance().mLongitude = mLongitude;
                        ASGpsManagerGms.getInstance().mLatitude = mLatitude;

                        Log.d(TAG, "mAddress: " + mAddress);
                        Log.d(TAG, "mLongitude: " + mLongitude);
                        Log.d(TAG, "mLatitude: " + mLatitude);

                        toCheckInOut();
                    }
                }
            }
        });
    }

    private void toCheckInOut() {
        try {
            if (mPresenter != null) {
                ZHISCheckInOutEntity zhisCheckInOutEntity = new ZHISCheckInOutEntity();
                zhisCheckInOutEntity.updateLocationInfo();
                mPresenter.checkInOut(getActivity(), zhisCheckInOutEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlerLoginResult() {
        try {
            if (ZHIMainProcessHelper.getInstance().getLoginEntity() != null) {
                //偷偷的上传通话记录
                if (ZHICallLogHelper.FLAG_OPEN) {
                    ZHICallLogHelper.getInstance().initAppUserIds(ZHIMainProcessHelper.getInstance().getLoginEntity().getUserId());
                }

                //人脸界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLiveFlag()) {
                    ZHIProjectRouter.toRegFaceV2();
                    return;
                }

                //客服界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerFlag()) {
                    //电召界面
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerWhitelistFlag()) {
                        ZHIProjectRouter.toRecallV2();
                        return;
                    }

                    //客服界面
                    ZHIProjectRouter.toCustomerServiceV2();
                    return;
                }

                //客服组长界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isCustomerDGroupFlag()) {
                    //客服界面
                    ZHIProjectRouter.toCustomerServiceAdmin();
                    return;
                }

                //电销界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isDxFlag()) {
                    ZHIProjectRouter.toRootTelemarketing();
                    return;
                }

                //电审界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isDhFlag()) {
                    ZHIProjectRouter.toRootDs();
                    return;
                }

                //单人审核界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isWholeKefuFlag()) {
                    ZHIProjectRouter.toRootAuditer();
                    return;
                }

                //大组长催收界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isBigGroupFlag()) {
                    ZHIProjectRouter.toRootBigGroup();
                    return;
                }

                //订单审核界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isOrderReviewFlag()) {
                    ZHIProjectRouter.toRootOrderReview();
                    return;
                }

                //催收界面
                if (ZHIMainProcessHelper.getInstance().getLoginEntity().isGroupFlag()) {
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB1()) {
                        ZHIProjectRouter.toRootGroupB1();
                    } else if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB2()) {
                        ZHIProjectRouter.toRootGroupB2();
                    } else {
                        ZHIProjectRouter.toRootGroup();
                    }
                } else {
                    if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB1()) {
                        ZHIProjectRouter.toRootMemberB1();
                    } else if (ZHIMainProcessHelper.getInstance().getLoginEntity().isLevelB2()) {
                        ZHIProjectRouter.toRootMemberB2();
                    } else {
                        ZHIProjectRouter.toRootMember();
                    }
                }

            } else {
                ZHIProjectRouter.toRegLoginV2();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void cleanTimer() {
        try {
            tv_ci_check_state.stopRun();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}